package com.yaoxun.console.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yaoxun.console.code.BaseResponseCode;
import com.yaoxun.console.service.UserService;
import com.yaoxun.console.xo.entity.LoginUser;
import com.yaoxun.console.xo.req.UserDeleteReq;
import com.yaoxun.console.xo.req.UserEditReq;
import com.yaoxun.console.xo.resp.ApiResp;
import com.yaoxun.console.xo.resp.BooResp;
import com.yaoxun.console.xo.resp.LoginUserResp;
import com.yaoxun.console.xo.resp.PageInfo;

@Controller
@RequestMapping("/user")
public class UserController implements BaseController {

	@Autowired
	private UserService userService;
	
	@GetMapping("/index.html")
	public String index() {
		return "sys/user/user-index";
	}
	
	@GetMapping("/add.html")
	public ModelAndView add() {
		ModelAndView mv = new ModelAndView("sys/user/user-edit");
		return mv;
	}
	
	@GetMapping("/update/{loginName}.html")
	public ModelAndView edit(@PathVariable String loginName) {
		ModelAndView mv = new ModelAndView("sys/user/user-edit");
		LoginUser user = userService.get(loginName);
		mv.addObject("obj", user);
		return mv;
	}
	
	
	@ResponseBody
	@PostMapping("/add")
	public ApiResp<BooResp> add(@Validated @RequestBody UserEditReq req) {
		
		userService.add(req);
		
		return ofRo(BaseResponseCode.ADD_SUCCESS, BooResp.of(true));
	}
	
	@ResponseBody
	@PostMapping("/update")
	public ApiResp<BooResp> update(@Validated @RequestBody UserEditReq req) {
		
		userService.update(req);
		
		return ofRo(BaseResponseCode.UPDATE_SUCCESS, BooResp.of(true));
	}
	
	@ResponseBody
	@PostMapping("/delete")
	public ApiResp<BooResp> delete(@Validated @RequestBody UserDeleteReq req) {
		
		userService.delete(req);
		
		return ofRo(BaseResponseCode.DELETE_SUCCESS, BooResp.of(true));
	}
	
	@ResponseBody
	@PostMapping("/list")
	public ApiResp<PageInfo<LoginUserResp>> list() {
		
		PageInfo<LoginUserResp> pageInfo = userService.list();
		
		return ofRo(BaseResponseCode.SEARCH_SUCCESS, pageInfo);
	}
	
}
